import {
    PipeTransform,
    Injectable,
    ArgumentMetadata,
    BadRequestException,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
import { AppI18nService } from '../../i18n/i18n.service';

@Injectable()
export class I18nValidationPipe implements PipeTransform<any> {
    constructor(private readonly i18nService: AppI18nService) { }

    async transform(value: any, { metatype }: ArgumentMetadata) {
        // 跳过 undefined/null 的验证，避免 "unknown value" 错误
        if (value === undefined || value === null) {
            return value;
        }

        if (!metatype || !this.toValidate(metatype)) {
            return value;
        }

        const object = plainToClass(metatype, value);
        const errors = await validate(object, {
            forbidUnknownValues: false,
            skipUndefinedProperties: true,
        });

        if (errors.length > 0) {
            const errorMessages = this.buildErrorMessages(errors);
            throw new BadRequestException(errorMessages);
        }

        return value;
    }

    private toValidate(metatype: Function): boolean {
        const types: Function[] = [String, Boolean, Number, Array, Object];
        return !types.includes(metatype);
    }

    private buildErrorMessages(errors: any[]): string[] {
        const messages: string[] = [];

        for (const error of errors) {
            if (error.constraints) {
                for (const constraint of Object.values(error.constraints)) {
                    messages.push(this.translateValidationMessage(constraint as string));
                }
            }

            if (error.children && error.children.length > 0) {
                const childMessages = this.buildErrorMessages(error.children);
                messages.push(...childMessages);
            }
        }

        return messages;
    }

    private translateValidationMessage(message: string): string {
        // 映射常见的验证错误消息到i18n键
        const messageMap: Record<string, string> = {
            'should not be empty': 'validation.required',
            'must be an email': 'validation.email',
            'must be longer than or equal to': 'validation.min_length',
            'must be shorter than or equal to': 'validation.max_length',
            'must be a number': 'validation.number',
            'must be a positive number': 'validation.positive',
            'must match': 'validation.invalid_format',
        };

        // 尝试找到匹配的i18n键
        for (const [key, i18nKey] of Object.entries(messageMap)) {
            if (message.includes(key)) {
                try {
                    return this.i18nService.getValidationMessage(i18nKey.replace('validation.', ''));
                } catch (error) {
                    return message; // 如果翻译失败，返回原始消息
                }
            }
        }

        // 如果无法映射，返回原始消息
        return message;
    }
}
